<template>
  <div>
    <HeaderNav title="栏目管理" />
    <div class="wrapper">
      <h2>点击删除一下频道</h2>
      <div class="active list">
        <div
          v-for="(category,index) in activeList"
          :key="category.id"
          class="item"
          @click="disableCategory(index)"
        >{{category.name}}</div>
      </div>
      <h2>点击添加一下频道</h2>
      <div class="deactive list">
        <div
          v-for="(category,index) in deactiveList"
          :key="category.id"
          class="item"
          @click="enableCategory(index)"
        >{{category.name}}</div>
      </div>
    </div>
  </div>
</template>

<script>
import HeaderNav from "@/components/HeaderNav";
export default {
  components: {
    HeaderNav,
  },
  data() {
    return {
      activeList: [],
      deactiveList: [],
    };
  },
  created() {
    // 保持数据步骤二, 本来每次进入都是重新获取栏目列表
    // 但是, 如果本地已经存放了以前的设定,
    // 就不应该重新获取, 而是从本地储存恢复数据
    if (localStorage.getItem("activeList")) {
      this.activeList = JSON.parse(localStorage.getItem("activeList"));
      if (localStorage.getItem("deactiveList")) {
        this.deactiveList = JSON.parse(localStorage.getItem("deactiveList"));
      }
    } else {
      // 如果本地没有数据, 才从远程获取全部列表
      // 默认设为都激活
      this.$axios({
        url: "/category",
      }).then((res) => {
        console.log(res.data);
        this.activeList = res.data.data;
      });
    }
  },
  watch: {
    activeList() {
      localStorage.setItem("activeList", JSON.stringify(this.activeList));
    },
    deactiveList() {
      localStorage.setItem("deactiveList", JSON.stringify(this.deactiveList));
    },
  },
  methods: {
    disableCategory(index) {
      // 在禁用一个栏目前, 先判断,激活列表最起码剩下一个以上的分类
      // 如果只剩下一个, 就不能再禁用了
      if (this.activeList.length == 1) {
        this.$toast("最少激活一个分类");
        return;
      }
      // 添加
      this.deactiveList.push(this.activeList[index]);
      this.activeList.splice(index, 1);
    },
    enableCategory(index) {
      this.activeList.push(this.deactiveList[index]);
      this.deactiveList.splice(index, 1);
    },
  },
};
</script>

<style lang="less" scoped>
.wrapper {
  padding: 10/360 * 100vw;
  h2 {
    font-size: 14/360 * 100vw;
    color: #888;
    font-weight: normal;
  }
  .list {
    display: flex;
    flex-wrap: wrap;
    .item {
      margin: 6/360 * 100vw;
      padding: 4/360 * 100vw 10/360 * 100vw;
      border: 1px solid #888;
    }
  }
}
</style>